//
//  BrandDetailsVC.m
//  phmall
//
//  Created by admin on 2017/11/29.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "BrandDetailsVC.h"
#import "FUIImageView.h"
#import "GoodsListCell.h"
#import "BrandModel.h"
#import "GoodsModel.h"
@interface BrandDetailsVC ()<UICollectionViewDelegate,UICollectionViewDataSource,GoodsListCellDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
{
    FUIImageView *seachV;
    NSInteger start;
}
@property(nonatomic,strong)UICollectionView  *collectionView;
@property(nonatomic,strong)NSMutableArray *goodsArray;
@property(nonatomic,strong)BrandModel *model;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation BrandDetailsVC
//-(void)moreAction:(UICollectionViewCell *)cell{
//    for (int i=0; i<10; i++) {
//        NSIndexPath *index1 =  [NSIndexPath indexPathForItem:i inSection:0];
//        HomeGoodsCell *goodsCell=(HomeGoodsCell *)[self.collectionView cellForItemAtIndexPath:index1];
//        if (cell!=goodsCell) {
//            [goodsCell moreViewTapAction];
//        }
//    }
//}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //搜索框
    seachV = [[FUIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-120, 30)];
    seachV.contentMode= UIViewContentModeScaleAspectFit;
    ViewBorderRadius(seachV, 5, 1, [UIColor colorWithHexString:@"#adadad"]);
    seachV.backgroundColor=[UIColor whiteColor];
    seachV.layer.cornerRadius = 5;
    seachV.userInteractionEnabled=YES;
    seachV.image=[UIImage imageNamed:@"搜索背景"];
    seachV.layer.masksToBounds=YES;
    self.navigationItem.titleView=seachV;
    if (IS_IOS_VERSION_11) {
        [seachV mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.height.offset(30);
        }];
    }
   
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(seachTapAction)];
    tapGesture.numberOfTapsRequired = 1;
    [seachV addGestureRecognizer:tapGesture];
    
    UIImageView *seach=[[UIImageView alloc]init];
    [seachV addSubview:seach];
    seach.image=[UIImage imageNamed:@"搜索"];
    seach.backgroundColor=[UIColor whiteColor];
    [seach mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(seachV).offset(10);
        make.height.width.offset(14);
        make.centerY.equalTo(seachV);
    }];
  
    
    UILabel *seachText=[[UILabel alloc]init];
    seachText.text=Localized(@"输入关键词");
    //    seachText.textColor=[UIColor groupTableViewBackgroundColor];
    seachText.font=[UIFont systemFontOfSize:13];
    [seachV addSubview:seachText];
    [seachText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(seach.mas_right).offset(5);
        make.height.offset(30);
        make.centerY.equalTo(seachV);
    }];
    
    
    UIBarButtonItem* rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:Localized(@"更多")] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarAction)];

    self.navigationItem.rightBarButtonItem= rightBar;
    
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    
    self.navigationItem.leftBarButtonItem=leftBar;
    
    [self loadDataWithBrand:YES];
    self.emptyType=EmptyDataSetNone;
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(0);
    }];
    // Do any additional setup after loading the view.

    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
    self.collectionView.mj_footer.hidden=YES;
    // Do any additional setup after loading the view.
}
-(void)HeaderRefresh{
    start=0;
    [self loadDataWithBrand:NO];
}
-(void)footeRefresh{
    start=self.goodsArray.count;
    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
}
-(void)rightBarAction{
    
}
-(void)seachTapAction{
    
}
- (void)loadDataWithBrand:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"brand_product/brand"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:self.uid forKey:@"cat"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            self.model=[BrandModel yy_modelWithDictionary:responseDict[@"data"][0]];
        }
        [self loadDataWithbrand_product:reload];
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.collectionView.mj_footer.hidden=YES;
        [self.goodsArray removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}
- (void)loadDataWithbrand_product:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"brand_product"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:self.uid forKey:@"cat"];
    [parametersDic setObject:@"0" forKey:@"start"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        if (start==0) {
            [self.goodsArray removeAllObjects];
            self.collectionView.mj_footer.hidden=YES;
        }
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        self.emptyType=EmptyDataSetNoData;
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            NSMutableArray *data=responseDict[@"data"];
            if (data.count==0) {
                [self.collectionView.mj_header endRefreshing];
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                if (reload) {
                    [self.collectionView reloadData];
                }
            }else{
                [self analysisDataWithBrandDictionary:data];
            }
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.collectionView.mj_footer.hidden=YES;
        [self.goodsArray removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}
- (void)analysisDataWithBrandDictionary:(NSMutableArray *)array{
    for (NSMutableDictionary *dict in array) {
        GoodsModel *model=  [GoodsModel yy_modelWithDictionary:dict];
        [self.goodsArray addObject:model];
    }
    if (self.goodsArray.count!=0) {
        //数量少于2条时隐藏上拉加载
        if (self.goodsArray.count<2) {
            self.collectionView.mj_footer.hidden=YES;
        }else{
            self.collectionView.mj_footer.hidden=NO;
        }
    }else{
        //数量为0条时隐藏上拉加载
        self.collectionView.mj_footer.hidden=YES;
    }
    [self.collectionView reloadData];
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}
#pragma mark collectionView代理方法

//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.goodsArray.count==0 ) {
        return 0;
    }else{
        return 1;
    }
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  
    return self.goodsArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, 90);
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    // 1.定义重用标识
    static NSString *headerID= @"reusableView";
    
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID forIndexPath:indexPath];
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
        for (UIView *view in headerView.subviews) {
            [view removeFromSuperview];
        }
        
        UIView *head=[[UIView alloc]init];
        head.backgroundColor=[UIColor whiteColor];
        [headerView addSubview:head];
        [head mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.offset(0);
            make.height.offset(90);
            make.top.offset(0);
        }];
        
       UIImageView *headImg=[[UIImageView alloc]init];
        [headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMGURL,self.model.logo]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
        [head addSubview:headImg];
        ViewBorderRadius(headImg, 5, 1, [UIColor groupTableViewBackgroundColor]);
        [headImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(10);
            make.top.offset(10);
            make.bottom.offset(-10);
            make.width.equalTo(headImg.mas_height);
        }];
        
        UILabel *name=[[UILabel alloc]init];
        name.text=self.model.brandname;
        name.font=[UIFont systemFontOfSize:15];
        [head addSubview:name];
        [name mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headImg.mas_right).offset(10);
            make.top.offset(15);
        }];
        
        UILabel *brandURL=[[UILabel alloc]init];
        brandURL.text=[NSString stringWithFormat:@"品牌网址:%@",self.model.weburl];
        brandURL.textColor=[UIColor orangeColor];
        brandURL.font=[UIFont systemFontOfSize:15];
        [head addSubview:brandURL];
        [brandURL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headImg.mas_right).offset(10);
            make.right.offset(-10);
            make.bottom.offset(-15);
        }];
        

        
        UIView *line=[[UIView alloc]init];
        [head addSubview:line];
        line.backgroundColor=[UIColor colorWithHexString:@"#ECEBEC"];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.offset(0);
            make.height.offset(0.5);
        }];
        return headerView;
    }
    return nil;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId=@"cell";
    GoodsListCell *cell = (GoodsListCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.model=self.goodsArray[indexPath.row];
    cell.delegate =self;
    ViewBorderRadius(cell, 10, 0, [UIColor clearColor]);
    return cell;
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (iPhone5SE) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 230);
    }else  if (iPhone6_6s) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }else  if (iPhone6Plus_6sPlus) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 272);
    }else{
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    for (int i=0; i<10; i++) {
//        NSIndexPath *index1 =  [NSIndexPath indexPathForItem:i inSection:0];
//        HomeGoodsCell *cell =  (HomeGoodsCell *)[_collectionView cellForItemAtIndexPath:index1];
//        [cell moreViewTapAction];
//    }
//    self.hidesBottomBarWhenPushed=YES;
//    CommodityDetailsVC *deta=[[CommodityDetailsVC alloc] init];
//    [self.navigationController pushViewController:deta animated:YES];
//    self.hidesBottomBarWhenPushed=NO;
}
//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            
            return [UIImage imageNamed:@"分类缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -(self.tabBar_height+44)/2;
}

- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:@"当前品牌暂无商品！\n先去其他地方逛逛吧。"];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, 9)];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange(9, 10)];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadDataWithBrand:YES];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.collectionView.contentOffset = CGPointZero;
}


-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //2.初始化collectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[GoodsListCell class] forCellWithReuseIdentifier:@"cell"];
        
        _collectionView.showsVerticalScrollIndicator=NO;
        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.emptyDataSetSource = self;
        _collectionView.emptyDataSetDelegate = self;
    }
    return _collectionView;
}
-(NSMutableArray *)goodsArray{
    if (!_goodsArray) {
        _goodsArray=[[NSMutableArray alloc]init];
    }
    return _goodsArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
